let init_choose = 0;
let animate_kess = 0;
let cantipago_child = 0;
/****样式*/
const varible_qjstyle_ys = `<style>input{background-color:#f7f7f7;border:1px solid #dcdcdc;padding:10px;border-radius:4px;font-size:16px;color:#333333;transition:background-color 0.3s ease}.container:hover{box-shadow:0 6px 12px rgba(0,0,0,0.15)}input:hover{background-color:#eaeaea}button{padding:10px 20px;background-color:#007bff;color:white;border:none;border-radius:4px;font-size:16px;cursor:pointer;transition:background-color 0.3s ease,transform 0.2s ease}textarea{background-color:#f7f7f7;border:1px solid #dcdcdc;padding:10px;border-radius:4px;font-size}
</style>`;
//** 新手引导**/
function guidedTour() {
  cantipago_child = 1;
  document.getElementById('wrapper').style.visibility = 'hidden';
  guidetoelement('h2#h2titlejmex', '双击这里修改试卷标题', function() {
  });
  document.querySelector('h2#h2titlejmex').addEventListener('dblclick', function() {
      document.querySelector('h2#h2titlejmex').removeEventListener('dblclick', arguments.callee);
      document.getElementById('wrapper').style.visibility = 'visible';
      nextStep_second();
  });
}


function guidetoelement(selector, message, callback) {
  const element = document.querySelector(selector);
  if (element) {
      const guideBox = document.createElement('div');
      guideBox.className = 'guide-box';
      guideBox.style.top = `${element.getBoundingClientRect().top + window.scrollY}px`;
      guideBox.style.left = `${element.getBoundingClientRect().left + window.scrollY}px`;
      guideBox.style.width = `${element.offsetWidth}px`;
      guideBox.style.height = `${element.offsetHeight}px`;
      document.body.appendChild(guideBox);
      if(animate_kess === 0){
        layer.msg(message, {time: 2500}); 
      }
      const zoomInAnimation = element.animate([
        { 
          transform: 'scale(1) translateZ(0px)', 
          filter: 'brightness(0.5)' 
        },
        { 
          transform: 'scale(0.8) translateZ(50px)', 
          filter: 'brightness(3)' 
        }
      ], {
        duration: 1500,
        iterations: 1,
        direction: 'alternate'
      });

      zoomInAnimation.onfinish = function() {
          guideBox.remove();
          if (callback) callback();
          animate_kess ++;
          if(animate_kess === 2){
            animate_kess = 0;
      }else{
        guidetoelement(selector, message, callback);
      }
      };
  }
}

function nextStep_second() {
  guidetoelement('button#choice_dxt', '选择一个题型，例如“单选题”，然后点击', function() {
  });
  document.querySelector('button#choice_dxt').addEventListener('click', function() {
    document.querySelector('button#choice_dxt').removeEventListener('click', arguments.callee);
      nextStep_third();
});
}
function nextStep_third() {
  guidetoelement('button#choice_tkt', '再次选择一个题型，例如“填空题”', function() {
  });
  document.querySelector('button#choice_tkt').addEventListener('click', function() {
    document.querySelector('button#choice_tkt').removeEventListener('click', arguments.callee);
      nextStep_four();
});
}
function nextStep_four() {
  guidetoelement('div#question_onechoice', '拖动第一个选择题至第二个填空题下', function() {
  });
  document.querySelector('div#question_onechoice').addEventListener('dragend', function(event) {
    var element = document.querySelector('div#question_onechoice');
    var parent = element.parentNode;
    var children = Array.from(parent.children);
    if (children.indexOf(element) !== 0) {
        document.querySelector('div#question_onechoice').removeEventListener('dragend', arguments.callee);
        nextStep_five();
    } else {
        layer.msg('拖动失败！位置不正确', {time: 1000});
    }
});
}
function nextStep_five() {
  guidetoelement('div#question_tkt', '右键第一道填空题,你将可以看到一个删除选项(但在这里没有必要)', function() {
  });
  document.querySelector('div#question_tkt').addEventListener('contextmenu', function(event) {
    document.querySelector('div#question_tkt').removeEventListener('contextmenu', arguments.callee);
      nextStep_six();
  });
}
function nextStep_six() {
  guidetoelement('div#question_onechoice input[typeo="opinion"]', '对第一道选择题中的其中任意一个选项双击，将其设置为正确答案', function() {
  });
  document.querySelector('div#question_onechoice input[typeo="opinion"]').addEventListener('dblclick', function(event) {
    document.querySelector('div#question_onechoice input[typeo="opinion"]').removeEventListener('dblclick', arguments.callee);
      nextStep_seven();
  });
}
function nextStep_seven() {
  layer.msg('多选题同理，选择多个选项（即正确答案）', {time: 1000});
  setTimeout(function(){
    layer.msg('恭喜您完成演示', {time: 1000});
  }, 1000);
  document.getElementById('btn_delques').disabled = false;
  cantipago_child = 0;
}
//** 新手引导**/
function delwithquestion(){
  layer.open({
    title: '操作提示',
    content: `'试卷设置'文本上方为您的试卷题目，双击即可修改
    </br>您可自由选择题型，点击即添加此题目到试卷中</br>
    右键题目可删除，拖动题目调整顺序</br>
    单选题：正确答案-双击此选项，多选题：双击多个选项即可</br>
    卷子设计完后请点击保存，并设置参数`,
    btn: ['操作演示','我会了'],
    yes: function(index, layero){
      layer.closeAll();
      document.getElementById('btn_delques').disabled = true;
      guidedTour();
    }
  });
}

function generatesj_zfchatrs(length) {
  var result = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;
  var usedChars = new Set();

  while (result.length < length) {
      var randomIndex = Math.floor(Math.random() * charactersLength);
      if (!usedChars.has(characters[randomIndex])) {
          result += characters[randomIndex];
          usedChars.add(characters[randomIndex]);
      }
  }
  return result;
}
//**********

function canvas_todara_creat(canvasElement) {
  const ctx = canvasElement.getContext('2d');
  let painting = false;
  let x = 0;
  let y = 0;

  function getMouseCoordinates(e) {
    const rect = canvasElement.getBoundingClientRect();
    return [e.clientX - rect.left, e.clientY - rect.top];
  }

  function draw(e) {
    if (!painting) return;
    const [x2, y2] = getMouseCoordinates(e);
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    [x, y] = [x2, y2];
  }

  canvasElement.addEventListener('mousedown', (e) => {
    painting = true;
    [x, y] = getMouseCoordinates(e);
    ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
    ctx.beginPath(); 
  });

  canvasElement.addEventListener('mouseup', () => {
    painting = false;
  });

  canvasElement.addEventListener('mousemove', (e) => {
    draw(e);
  });
}
//绘画函数
function add_newquestion(type) { //左侧题栏
  const questionnaire = document.getElementById('questionnaire');
  const question = document.createElement('div');
  question.className = 'question';
  let questionContent;
  init_choose ++;
  switch (type) {
    case 'text':
      questionContent = `
        <input  id="${generatesj_zfchatrs(5)}" type="text" axhs="title_exam" placeholder="题目标题">
        <textarea id="${generatesj_zfchatrs(5)}" axhs="title_exam" placeholder="在这里输入题目描述"></textarea>
        <input type="text" id="${generatesj_zfchatrs(6)}" class="bzda_dwb" placeholder="请输入标准答案">
      `;
      question.id = `question_tkt`;
      break;
    case 'textarea':
      questionContent = `
         <input id="${generatesj_zfchatrs(5)}" axhs="title_exam" type="text" placeholder="题目标题">
        <textarea  id="${generatesj_zfchatrs(5)}"  axhs="title_exam" placeholder="在这里输入问题描述" rows="4"></textarea>
      `;
      question.id = `question_gst`;
      break;
    case 'radio':
      questionContent = `
        <input  id="${generatesj_zfchatrs(5)}" axhs="title_exam" type="text" placeholder="题目标题">
        <textarea  id="${generatesj_zfchatrs(5)}" axhs="title_exam"  placeholder="在这里输入问题描述"></textarea>
        <div class="options">
          <input type="text" id="${generatesj_zfchatrs(5)}" typeo="opinion" placeholder="选项1">
          <input type="text" id="${generatesj_zfchatrs(5)}" typeo="opinion" placeholder="选项2">
          <button onclick="addnew_option(this)">添加选项</button>
        </div>
      `;
      question.id = `question_onechoice`;
      break;
    case 'checkbox':
      questionContent = `
        <input id="${generatesj_zfchatrs(5)}" axhs="title_exam"  type="text" placeholder="题目标题">
        <textarea  id="${generatesj_zfchatrs(5)}" axhs="title_exam" placeholder="在这里输入问题描述"></textarea>
        <div class="options">
          <input type="text" id="${generatesj_zfchatrs(5)}" typeo="opinion" placeholder="选项1">
          <input type="text" id="${generatesj_zfchatrs(5)}" typeo="opinion" placeholder="选项2">
          <button onclick="addnew_option(this)">添加选项</button>
        </div>
      `;
      question.id = `question_morechoice`;
      break;
    case 'dtbefore':
      questionContent = `
      <input id="${generatesj_zfchatrs(5)}" axhs="title_exam"  type="text" placeholder="答题须知-标题">
        <textarea  id="${generatesj_zfchatrs(5)}" axhs="title_exam" placeholder="答题须知-内容"></textarea>
        `;
        question.id = `question_dtbefore`;
        question.setAttribute('_dmpoint', 1);
        break;
    case 'paintin':
      questionContent = `
      <input id="${generatesj_zfchatrs(5)}" axhs="title_exam"  type="text" placeholder="题目标题">
        <textarea  id="${generatesj_zfchatrs(5)}" axhs="title_exam" placeholder="在这里输入问题描述"></textarea>
        <canvas id="${generatesj_zfchatrs(5)}" width="1040" height="150"></canvas>
        `;
        question.id = `question_paintin`;
        break;
    case 'infortoget':
      questionContent = `
      <input id="${generatesj_zfchatrs(5)}" axhs="title_exam"  type="text" placeholder="收集信息-标题">
        `;
        question.id = `question_infortoget`;
        question.setAttribute('_dmpoint', 1);
        break;
    case 'infor_dlsm':
      questionContent = `
      <textarea  id="${generatesj_zfchatrs(5)}" axhs="title_exam" placeholder="段落说明内容"></textarea>
        `;
        question.id = `question_infor_dlsm`;
        question.setAttribute('_dmpoint', 1);
        break;
    case 'codeins':
      questionContent = `
      <input id="${generatesj_zfchatrs(5)}" axhs="title_exam"  type="text" placeholder="编程语言">
      <textarea  id="${generatesj_zfchatrs(5)}" axhs="title_exam" placeholder="请输入题目描述"></textarea>
        `;
        question.id = `question_codeins`;
        break;
  }
  question.setAttribute('tystatus', generatesj_zfchatrs(6));
  if(type === 'dtbefore'){
    if(document.querySelector(`[id="question_dtbefore"]`)){
      layer.msg('您已添加过答题须知，请勿重复添加', {time: 1000});
      init_choose--;
      return;
    }
    init_choose--;
    question.innerHTML = `<h3>答题须知</h3>`+questionContent;
    question.draggable = false;
  }else if(type === 'paintin'){
      question.innerHTML = `<h3>第${init_choose}题</h3>`+questionContent;
      let canvas = question.querySelector('canvas');
      var ctx = canvas.getContext('2d');
      ctx.fillStyle = "#FF0000";
      ctx.font = "20px Arial";
      ctx.textAlign="center";
      ctx.fillText('答题区域',canvas.width/2,canvas.height/2);
      canvas_todara_creat(canvas);
  }
  else{
    question.innerHTML = `<h3>第${init_choose}题</h3> `+questionContent;
    question.draggable = true;
  }
  question.addEventListener('contextmenu', function(e) {
      hideorshowsibcon(e,question.getAttribute('tystatus'));
      e.stopPropagation();
  });
  if(type !== 'dtbefore'){ //像答题须知题目类型，不需要添加到末尾
      questionnaire.appendChild(question);
      if(type === 'codeins'){
        codetips_inputtobind(question.querySelector('input').id);
      }
  }else{
    questionnaire.insertBefore(question, document.querySelector(`[class="question"]`));
  }
}
let nowmenushowbything;
function hideorshowsibcon(e,id){
  e.preventDefault(); 
    document.querySelector(`[tystatus="${id}"]`).classList.add('highlight');
    nowmenushowbything = document.querySelector(`[tystatus="${id}"]`);
    if(nowmenushowbything.getAttribute('_dmpoint')){ //像答题须知等等题目类型，不需要分数功能
      document.getElementById('point_to_li_menu').style.display = 'none';
      document.getElementById('point_to_lisame_menu').style.display = 'none';
    }else{
      document.getElementById('point_to_li_menu').style.display = 'block';
      document.getElementById('point_to_lisame_menu').style.display = 'block';
    }
    nowmenushowbything2 = id;
      var x = e.clientX;
      var y = e.clientY;
      document.getElementById('contextMenu').style.display = 'block';
      document.getElementById('contextMenu').style.left = x + 'px';
      document.getElementById('contextMenu').style.top = y + 'px';
      document.addEventListener('click', function hideMenu() {
          document.getElementById('contextMenu').style.display = 'none';
          document.querySelector(`[tystatus="${id}"]`).classList.remove('highlight');
          document.removeEventListener('click', hideMenu);
  });
  e.stopPropagation();
}
  function addnew_option(button) { //添加新选项
    const options = button.parentNode;
    const newOption = document.createElement('input');
    newOption.type = 'text';
    newOption.setAttribute('typeo','opinion');
    newOption.setAttribute('id',generatesj_zfchatrs(5))
    newOption.placeholder = '新选项';
    options.insertBefore(newOption, button);
  }
//---------------------------------------------------
let newerexamjname = '';
let olderexamjname = document.getElementById('h2titlejmex').innerText;
document.addEventListener('dblclick', function(event) {
    var target = event.target;
    if (target.tagName === 'INPUT' && target.getAttribute('typeo') === 'opinion' ) {
        let parent = target.parentElement;
let parent2 = parent.parentElement;
let parent2_id = parent2.getAttribute('id');
if (parent2_id === 'question_onechoice') {
    let siblings = Array.from(parent.children);
    siblings.forEach(sibling => {
        if (sibling !== target) {
            sibling.style.backgroundColor = ''; 
            sibling.removeAttribute('typeos'); 
        }
    });
        target.style.backgroundColor = '#008cff';
        target.setAttribute('typeos', 'answer');
}else if (parent2_id === 'question_morechoice') {
    if (target.getAttribute('typeos') === 'answer') {
        target.style.backgroundColor = '';
        target.removeAttribute('typeos');
        return;
    }
    target.style.backgroundColor = '#008cff';
    target.setAttribute('typeos', 'answer');
}
    event.stopPropagation();
    }else if (target.getAttribute('jiukt') === 'hntitle') {
      if(cantipago_child === 1){
        return false;
      }
        olderexamjname = target.innerText;
        layer.confirm('确定修改吗？当前卷名为：'+olderexamjname, {
            btn: ['确定','取消'] 
         }, function(){
            layer.closeAll();
            layer.prompt({title: '请输入新卷名', formType: 2}, function(pass, index){
                target.innerText = pass;
                newerexamjname = pass;
                layer.alert('修改成功');
                layer.close(index);
            });
         }, function(){});
    }
}, false); 
function deloneinexamof(){ //菜单删除one题
    layer.confirm('确定删除吗？', {
        btn: ['确定','取消'] 
     }, function(){
        nowmenushowbything.remove();
        layer.closeAll();
        reorderh3_afdel();
        if(nowmenushowbything.id === 'question_dtbefore'){ //是否在其
          return;
        } 
        init_choose --;
     });
}
function reorderh3_afdel(){ //重新排序h3
  var questions = document.querySelectorAll('.question');
    questions.forEach(function(question, index) {
        var h3 = question.querySelector('h3');
        if (h3) {
            h3.textContent = '第' + (index + 1)+'题'; 
        }
    });
}
/***********************Init******************************/
let nowid = document.getElementById('choslandna_saa').innerText;
yhload.loadqr_show('questionnaire');
init_cshbeok();
function fillalldataceraddlisten(){
  const container = questionnaire;
  const childDivs = container.querySelectorAll('div');
  Array.from(childDivs).forEach((div) => {
    if (!div.querySelector('div') && div.id !== 'question_dtbefore') {
      init_choose++;
    }
      div.addEventListener('contextmenu', function(e) {
        hideorshowsibcon(e, this.getAttribute('tystatus'));
        e.stopPropagation();
      });
  });
}
function fillfromdatajson(jsonData) {
  for (const typeStatus in jsonData) {
    if (jsonData.hasOwnProperty(typeStatus)) {
      const fieldsArray = jsonData[typeStatus];
      fieldsArray.forEach(fields => {
        for (const key in fields) {
          if (fields.hasOwnProperty(key)) {
            const element = document.getElementById(key);
            if (element) {
              element.value = fields[key];
            }
          }
        }
      });
    }
  }
}
function canvas_loading_creat(){
  var allcanvas = document.querySelectorAll('canvas');
  allcanvas.forEach(function(canvas){
    var ctx = canvas.getContext('2d');
        ctx.fillStyle = "#FF0000";
        ctx.font = "20px Arial";
        ctx.textAlign="center";
        ctx.fillText('答题区域',canvas.width/2,canvas.height/2);
        canvas_todara_creat(canvas);
  });
}
function loading_intoquescon(data){
  questionnaire.innerHTML = data[0].exmattm;
  let jsonb = data[0].exmatanse;
  var jsonObj = JSON.parse(jsonb);
  fillfromdatajson(jsonObj);
  fillalldataceraddlisten();
  canvas_loading_creat(); //初始化canvas画板
}
function init_cshbeok(){
  const formData = new FormData();
    formData.append('nowid', nowid);
    fetch('exam/getupdate.php', {
        method: 'POST',
        body: formData
    })
    .then(function (response) {
        return response.json();
    }).then(function (data) {
        if(data.code === 1){
            loading_intoquescon(data.data);
        }else{
            layer.alert('加载失败');
        }
        yhload.loadqr_hide('questionnaire');
    });   
}
/***********************保存******************************/
function emmationsetttingparm(){
  layer.open({
    type: 2,
    title:'设置',
    area: ['400px', '375px'],
    content: 'otpage/update.html?'+nowid
  });
}
function saveallanswerandinfo() {
  const container = questionnaire;
  const formData = {};
  container.querySelectorAll('div').forEach(div => {
    const typeStatus = div.getAttribute('tystatus');
    if (typeStatus !== null && typeStatus !== 'null') {
      if (!formData[typeStatus]) {
        formData[typeStatus] = [];
      }
      Array.from(div.querySelectorAll('input, textarea')).forEach(input => {
        const key = input.id;
        const value = input.value.trim(); 
        if (value !== '') { 
          formData[typeStatus].push({ [key]: value });
        }
      });
    }
  });
  if (formData['null']) {
    delete formData['null'];
  }
  const jsonResult = JSON.stringify(formData, null, 2);
  return jsonResult;
}
function saveexamnowin(){
  let nowlastname = 'not';
  if(newerexamjname !== ''){
    nowlastname = newerexamjname;
  }
  let justbill = saveallanswerandinfo();
  let allhtml = questionnaire.innerHTML;
  const formData = new FormData();
    formData.append('newname', nowlastname);
    formData.append('allhtml', allhtml);
    formData.append('nowid', nowid);
    formData.append('justbill', justbill);
    fetch('exam/keepnew.php', {
        method: 'POST',
        body: formData
    })
    .then(function (response) {
        return response.json();
    }).then(function (data) {
        if(data.status === 200){
            layer.alert('保存成功');
            setTimeout(function(){window.location.href = './';},2000);
        }else{
            layer.alert('保存失败');
        }
    });   
}
/***********************控制题目移动******************************/
function please_tomove_thanks() {
  let moveElement = document.querySelector(`[tystatus="${nowmenushowbything2}"]`);
  let moveNumber = 1;
  layer.prompt({
    title: '请输入移动到第几题',
    formType: 3 
  }, function(text, index) {
    moveNumber = parseInt(text)+1; 
    layer.close(index); 
    if (!isNaN(moveNumber) && moveNumber > 0) {
      let targetElement = null;
      let container = moveElement.parentNode;
      let questions = container.querySelectorAll('.question');
      for (let i = 0; i < questions.length; i++) {
        if (i + 1 === moveNumber) {
          targetElement = questions[i];
          break;
        }
      }
      if (targetElement && targetElement !== moveElement) {
        let parent = moveElement.parentNode;
        parent.insertBefore(moveElement, targetElement);
        updatequestionnumber(parent);
      }
    }
  });
}
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    init_runagian();
  });
});
var config = {
  attributes: true, 
  childList: true, 
  subtree: true 
};
observer.observe(questionnaire, config);
function init_runagian() { // 重置绑定
  document.querySelectorAll('.question').forEach(question => {
    question.addEventListener('dragstart', function(e) {
      e.dataTransfer.setData('text/plain', this.getAttribute('tystatus'));
    });

    question.addEventListener('dragover', function(e) {
      e.preventDefault(); 
    });

    question.addEventListener('drop', function(e) {
      e.preventDefault();
      const draggedId = e.dataTransfer.getData('text/plain');
      const draggedElement = document.querySelector(`[tystatus="${draggedId}"]`);
      const currentElement = this;

      if (currentElement.nextElementSibling && currentElement.nextElementSibling.getAttribute('tystatus') === draggedId) {
        return;
      }

      const parent = currentElement.parentNode;
      
      parent.insertBefore(draggedElement, currentElement.nextSibling);

      updatequestionnumber(parent);
    });
  });
}
function updatequestionnumber(container) {
  let count = 1;
  container.querySelectorAll('.question').forEach(question => {
    if(question.id === "question_dtbefore"){
      return;
    }
    question.querySelector('h3').textContent = `第${count}题`;
    count++;
  });
}

// 初始化-右键设置分数按钮
function setting_point(){
  var quesyaks = document.querySelector(`[tystatus="${nowmenushowbything2}"]`);
  layer.open({
      type: 1, 
      area: ['500px', '300px'],
      title: '设置分数',
      shade: 0.6, 
      shadeClose: true, 
      maxmin: true, 
      anim: 0, 
      content: ` 
  ${varible_qjstyle_ys}
      <label for="btjx">本题解析</label>
      <input type="text" id="btjx" value="" >
      </br>
       <label for="btdfz">本题分数</label>
      <input type="text" id="btdfz" value="" >
          <button id="buttons"  type="button">修改</button>`,
      success: function (layero, index) {
          var dondothisdebug = false;
          document.getElementById('btjx').value = quesyaks.getAttribute('btjx');
          document.getElementById('btdfz').value = quesyaks.getAttribute('btdfz');
          if(quesyaks.getAttribute('ghj')==='f'){
              document.getElementById('btdf').value = 0;
              document.getElementById('btdf').disabled = true;
          }
          if(quesyaks.getAttribute('ghj')==='t'){
              dondothisdebug = true;
              document.getElementById('btdf').disabled = true;
          }
          document.getElementById('buttons').onclick = function () {
              if(dondothisdebug){
                  document.getElementById('btdf').value = document.getElementById('btdfz').value;
              }
              if(document.getElementById('btdfz').value === ''){
                  layer.msg('请先输入分数');
                  return;
              }
              quesyaks.setAttribute('btjx', document.getElementById('btjx').value);
              quesyaks.setAttribute('btdfz', document.getElementById('btdfz').value);
              layer.close(index);
          }
      }
    });
}
let nowmenushowbything2 = null;
function setting_moudle(){
  var quesyaks = document.querySelector(`[tystatus="${nowmenushowbything2}"]`);
  var zpoints = quesyaks.getAttribute('btdfz');
  var id = quesyaks.id;
  var divs = document.querySelectorAll(`div[id="${id}"]`);
  divs.forEach(function(div) {
      if(div.getAttribute('tystatus') !== quesyaks.getAttribute('tystatus')){
          div.setAttribute('btdfz', zpoints);
      }
  });
}
//----------------------下为keyword-代码提示
var codetips_data = [
  { value: "Python", description: "一种广泛使用的高级编程语言，以其简洁易读的语法和强大的库支持而著称" },
  { value: "JavaScript", description: "一种广泛用于Web开发的脚本语言，支持客户端和服务器端编程" },
  { value: "Java", description: "一种面向对象的编程语言，具有跨平台特性，广泛应用于企业级应用开发" },
  { value: "C++", description: "一种高效、灵活的编程语言，支持面向过程和面向对象编程" },
  { value: "C#", description: "微软开发的一种面向对象的编程语言，主要用于.NET框架下的应用开发" },
  { value: "Go", description: "一种编译型、并发型、具有垃圾回收功能的编程语言，设计简单、高效" },
  { value: "Rust", description: "一种系统编程语言，以其内存安全性和并发性而著称" },
  { value: "Kotlin", description: "一种用于JVM、Android和原生平台的静态类型编程语言，简洁、安全" }
];
function codetips_inputtobind(yougivemeid){
  var input = document.getElementById(yougivemeid);
  var autocompleteList = document.getElementById('autocomplete-list');
  var currentFocus;
  input.addEventListener('input', function(e) {
      var a, b, i, val = this.value;
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      a = document.createElement("div");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      input.parentNode.appendChild(a);
      for (i = 0; i < codetips_data.length; i++) {
          if (codetips_data[i].value.substr(0, val.length).toUpperCase() == val.toUpperCase()) {
              b = document.createElement("div");
              b.innerHTML = "<strong>" + codetips_data[i].value.substr(0, val.length) + "</strong>";
              b.innerHTML += codetips_data[i].value.substr(val.length);
              b.innerHTML += " - " + codetips_data[i].description;
              b.innerHTML += "<input type='hidden' value='" + codetips_data[i].value + "'>";
              b.addEventListener("click", function(e) {
                  input.value = this.getElementsByTagName("input")[0].value;
                  closeAllLists();
              });
              a.appendChild(b);
          }
      }
  });

  input.addEventListener('keydown', function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
          currentFocus++;
          addActive(x);
      } else if (e.keyCode == 38) {
          currentFocus--;
          addActive(x);
      } else if (e.keyCode == 13) {
          e.preventDefault();
          if (currentFocus > -1) {
              if (x) x[currentFocus].click();
          }
      }
  });

  function addActive(x) {
      if (!x) return false;
      removeActive(x);
      if (currentFocus >= x.length) currentFocus = 0;
      if (currentFocus < 0) currentFocus = (x.length - 1);
      x[currentFocus].classList.add("autocomplete-active");
  }

  function removeActive(x) {
      for (var i = 0; i < x.length; i++) {
          x[i].classList.remove("autocomplete-active");
      }
  }

  function closeAllLists(elmnt) {
      var x = document.getElementsByClassName("autocomplete-items");
      for (var i = 0; i < x.length; i++) {
          if (elmnt != x[i] && elmnt != input) {
              x[i].parentNode.removeChild(x[i]);
          }
      }
  }

  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
  });
}
